﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// DecoratorControl surrounds the contents of a control with the contents of a Template control.
    /// </summary>
    [ParseChildren(false)]
    public class DecoratorControl : Control, INamingContainer
    {
        /// <summary>
        /// The name of the .ascx file to load as a template.
        /// </summary>
        public string Template { get; set; }

        private ControlCollection ControlBin ;

        protected override void AddParsedSubObject(object obj)
        {
            if(ControlBin == null)
            {
                ControlBin = new ControlCollection(this);
            }

            if (obj is Control)
            {
                ControlBin.Add((Control)obj);
            }
            else
            {
                //
            }
        }

        protected override void OnInit(EventArgs e)
        {
            this.ApplyLayout();
            base.OnInit(e);            
        }

        private void ApplyLayout()
        {
            Controls.Clear();

            //load the template.
            Control _tpl = TemplateControl.LoadControl(this.Template);
            _tpl.ID = this.ID + "_template";
            this.Controls.Add(_tpl);
            OnTemplateLoaded(_tpl);

            //find the content placeholder.
            Control content = _tpl.FindControl("Contents");

            if (content == null)
            {
                throw new Exception("The loaded template '" + this.Template + "' does not contain a control with ID 'Contents'.");
            }

            //move all childs of this page's FORM object as childs of the template's content block.
            for (int i = 0; i < ControlBin.Count; i++)
            {
                content.Controls.Add(ControlBin[i]);
            }
        }

        protected virtual void OnTemplateLoaded(Control template)
        {
        }
    }
}
